package com.wakala.employment.fragment.profile;

import static com.xuexiang.xutil.XUtil.getContext;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.leaf.library.StatusBarUtil;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.wakala.employment.MyApp;
import com.wakala.employment.R;
import com.wakala.employment.adapter.JobInfoListAdapter;
import com.wakala.employment.adapter.base.broccoli.BroccoliRecyclerAdapter;
import com.wakala.employment.adapter.base.broccoli.BroccoliSimpleDelegateAdapter;
import com.wakala.employment.adapter.bean.JobInfoPage;
import com.wakala.employment.adapter.entity.JobInfoVo;
import com.wakala.employment.core.BaseFragment;
import com.wakala.employment.core.constants.UserRoleEnum;
import com.wakala.employment.core.http.subscriber.NoTipRequestSubscriber;
import com.wakala.employment.databinding.FragmentCollectionJobListBinding;
import com.wakala.employment.fragment.finder.JobInfoFragment;
import com.wakala.employment.http.TestApi;
import com.wakala.employment.http.bean.CollectionPage;
import com.wakala.employment.http.bean.CollectionRecordVo;
import com.wakala.employment.utils.DemoDataProvider;
import com.xuexiang.xhttp2.XHttpProxy;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xpage.utils.GsonUtils;
import com.xuexiang.xui.adapter.recyclerview.RecyclerViewHolder;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.utils.ThemeUtils;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.data.DateUtils;
import com.xuexiang.xutil.tip.ToastUtils;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.List;

import me.samlss.broccoli.Broccoli;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link CollectionJobListFragment#} factory method to
 * create an instance of this fragment.
 */
@Page(anim = CoreAnim.none)
public class CollectionJobListFragment extends BaseFragment<FragmentCollectionJobListBinding> implements View.OnClickListener {

    private String TAG = CollectionJobListFragment.class.getSimpleName();

    int page = 1;
    int pageSize = 10;
    RecyclerView recyclerView;
    SmartRefreshLayout refreshLayout;

    private BroccoliRecyclerAdapter<CollectionRecordVo> mJobsAdapter;
    private List<CollectionRecordVo> jobInfoVoList = new ArrayList<>();

    @NonNull
    @Override
    protected FragmentCollectionJobListBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        return FragmentCollectionJobListBinding.inflate(inflater, container, attachToRoot);
    }


    @Override
    protected TitleBar initTitle() {
        TitleBar titleBar = super.initTitle();
        if (MyApp.User_Role == UserRoleEnum.CANDIDATE) {
            titleBar.setTitle("收藏职位");
        } else if (MyApp.User_Role == UserRoleEnum.BOOS) {
            titleBar.setTitle("收藏工人");
        }

        titleBar.setTitleColor(R.color.black);
        titleBar.setLeftTextColor(R.color.black);
        titleBar.setLeftImageDrawable(getResources().getDrawable(R.drawable.icon_arrow_back));
        titleBar.setBackgroundResource(R.color.white);//设置标题栏背景颜色
        StatusBarUtil.setDarkMode(getActivity());
        //设置状态栏背景颜色，如果设置为 Color.TRANSPARENT 将会隐藏状态栏
        getActivity().getWindow().setStatusBarColor(getResources().getColor(R.color.white));
        return titleBar;
    }


    @Override
    protected void initViews() {
        jobInfoVoList = DemoDataProvider.getEmptyCollectionRecord();
        mJobsAdapter = new BroccoliRecyclerAdapter<CollectionRecordVo>(jobInfoVoList) {
            @Override
            protected int getItemLayoutId(int viewType) {
                return R.layout.adapter_jobs_collection_card_view_list_item;
            }

            @Override
            protected void onBindData(RecyclerViewHolder holder, CollectionRecordVo model, int position) {
                if (model != null) {
                    //holder.text(R.id.tv_tag, model.getJobTags());
                    holder.text(R.id.tv_title, model.getTitle());
                    holder.text(R.id.tv_summary, model.getContent());
                    holder.text(R.id.tv_job_time, model.getPublishTime().subSequence(0, 16));
                    holder.text(R.id.tv_location, model.getJobAddressName());
                    //Tag容器
                    com.xuexiang.xui.widget.flowlayout.FlowLayout tagLayout = holder.findViewById(R.id.tag_layout);
                    tagLayout.setTag(model.getId());
                    tagLayout.removeAllViews();
                    //
                    addTag(tagLayout, model.getJobCityName(), "blue");
                    addTag(tagLayout, model.getJobCategoryName(), "gray");

                    //holder.click(R.id.card_view, v -> Utils.goWeb(getContext(), model.getDetailUrl()));
                    holder.click(R.id.card_view, view -> {
                        openNewPage(JobInfoFragment.class, "jobInfoId", model.getId());
                        //openNewPage(JobInfoFragment.class, "jobInfo", model);
                    });
                }
            }

            @Override
            protected void onBindBroccoli(RecyclerViewHolder holder, Broccoli broccoli) {
                broccoli.addPlaceholders(
                        holder.findView(R.id.tv_job_time),
                        holder.findView(R.id.tv_title),
                        holder.findView(R.id.tv_summary),
                        holder.findView(R.id.tag_layout),
                        holder.findView(R.id.iv_location),
                        holder.findView(R.id.tv_location),
                        holder.findView(R.id.tv_tag_demo),
                        holder.findView(R.id.btn_cancel_collect),
                        holder.findView(R.id.btn_attention_boos)
                );
            }
        };

        recyclerView = binding.recyclerView;
        refreshLayout = binding.refreshLayout;
        // 初始化RecyclerView
        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        viewPool.setMaxRecycledViews(0, 20);
        recyclerView.setRecycledViewPool(viewPool);
        WidgetUtils.initRecyclerView(recyclerView, DensityUtils.dp2px(getContext(), 5), ThemeUtils.resolveColor(getContext(), R.attr.xui_config_color_background));

        recyclerView.setAdapter(mJobsAdapter);

    }

    private void addTag(com.xuexiang.xui.widget.flowlayout.FlowLayout linearLayout, String tagName, String themName) {
        TextView textView = new TextView(linearLayout.getContext());
        ViewGroup.MarginLayoutParams textViewParams = new ViewGroup.MarginLayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, // 宽度
                ViewGroup.LayoutParams.WRAP_CONTENT  // 高度
        );
        textViewParams.setMargins(DensityUtils.dp2px(getContext(), 5), 0, 0, DensityUtils.dp2px(getContext(), 5));
        textView.setPadding(DensityUtils.dp2px(getContext(), 2), DensityUtils.dp2px(getContext(), 2), DensityUtils.dp2px(getContext(), 2), DensityUtils.dp2px(getContext(), 2));
        textView.setLayoutParams(textViewParams);
        textView.setText(tagName);
        textView.setTextSize(12.0f);

        if ("blue".equals(themName)) {
            textView.setBackgroundColor(linearLayout.getResources().getColor(R.color.tag_bg_blue));
            textView.setTextColor(linearLayout.getResources().getColor(R.color.colorPrimary));
        } else if ("gray".equals(themName)) {
            textView.setBackgroundColor(linearLayout.getResources().getColor(R.color.tag_bg_gray));
            textView.setTextColor(linearLayout.getResources().getColor(R.color.tag_text_gray));
        } else {
            textView.setBackgroundColor(linearLayout.getResources().getColor(R.color.tag_bg_blue));
            textView.setTextColor(linearLayout.getResources().getColor(R.color.colorPrimary));
        }
        linearLayout.addView(textView);
    }

    @Override
    protected void initListeners() {
        initRecycleView();
    }

    private void initRecycleView() {
        //下拉刷新
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            page = 1;
            getCollectionList("fresh");

        });
        //上拉加载
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            int currentPage = mJobsAdapter.getItemCount() / pageSize + 1;
            page = currentPage + 1;
            getCollectionList("more");
        });
        //设置刷新加载时禁止所有列表操作
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.autoRefresh();//第一次进入触发自动刷新，演示效果
        //
    }


    @Override
    public void onClick(View view) {

    }

    @SuppressLint("CheckResult")
    private void getCollectionList(String type) {
        appLoadingDialog.show();
        XHttpProxy.proxy(TestApi.IOther.class).getCollectionList(0, page).subscribeWith(new NoTipRequestSubscriber<CollectionPage>() {
            @Override
            protected void onSuccess(CollectionPage commonPageApiResult) {
                Log.i(TAG, "-------------收藏信息列表------------------");
                Log.i(TAG, GsonUtils.toJson(commonPageApiResult));
                if (type.equals("fresh")) {
                    mJobsAdapter.refresh(commonPageApiResult.getList());
                    binding.refreshLayout.finishRefresh();
                    if (commonPageApiResult.getList().isEmpty()) {
                        binding.llStateful.showEmpty();
                    } else {
                        binding.llStateful.showContent();
                    }
                } else if (type.equals("more")) {
                    if (commonPageApiResult.getList().isEmpty()) {
                        binding.refreshLayout.finishLoadMoreWithNoMoreData();
                        ToastUtils.toast("已更新到最新数据");
                    } else {
                        mJobsAdapter.loadMore(commonPageApiResult.getList());
                        binding.refreshLayout.finishLoadMore();
                    }

                }
                appLoadingDialog.dismiss();
                ToastUtils.toast("已更新最新数据");
                Log.i(TAG, "-------------收藏信息列表------------------");
            }

            @Override
            public void onError(ApiException e) {
                super.onError(e);
                appLoadingDialog.dismiss();
                if (type.equals("fresh")) {
                    binding.refreshLayout.finishRefresh();
                } else {
                    binding.refreshLayout.finishLoadMore();
                }
                binding.llStateful.showError("网络访问服务器异常", "重试", view -> getCollectionList("fresh"));


                ToastUtils.toast(e.getDisplayMessage());
                Log.i(TAG, "-------------收藏信息列表-返回错误------------------");
                Log.e(TAG, e.getMessage());
            }

        });

    }
}